<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
      size="small"
      class="ry_form"
    >
      <el-form-item :label="$t('common.status')" prop="status">
        <el-select v-model="queryParams.status" clearable>
          <el-option v-for="item in statusList" :key="item.index" :label="item.label" :value="item.value" />
        </el-select>
        </el-form-item>
      <el-form-item class="flex_one tr">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >{{ $t('common.search') }}</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >{{ $t('common.reset') }}</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-if="YT_roles"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >{{ $t('common.add') }}</el-button
        >
        <el-button type="primary" plain icon="el-icon-upload2" size="mini" @click="beforeHandleExport"
          >{{ $t('common.export') }}</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
        :columns="columns"
      ></right-toolbar>
    </el-row>
    <WmsTable
      v-loading="loading"
      :data="wmStockAgeList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        :label="$t('fiance.payee')"
        align="center"
        prop="payeeName"
        v-if="columns[0].visible"
      />
      <el-table-column
        :label="$t('fiance.drawee')"
        align="center"
        prop="payerName"
        v-if="columns[1].visible"
      />
      <el-table-column
        :label="$t('fiance.total')"
        align="center"
        prop="amount"
        v-if="columns[2].visible"
      />
      <el-table-column
        :label="$t('common.status')"
        align="center"
        prop="status"
        v-if="columns[3].visible"
      >
      <template slot-scope="scope">
        <el-tag v-if="scope.row.status === 'YCZ'" effect="plain">{{ $t('fiance.YCZ') }}</el-tag>
        <el-tag v-if="scope.row.status === 'WRITE_OFF'" type="success" effect="plain">{{ $t('fiance.WRITEOFF') }}</el-tag>
        <el-tag v-if="scope.row.status === 'INVALID'" type="danger" effect="plain">{{ $t('fiance.INVAILD') }}</el-tag>
      </template>
      </el-table-column>
      <el-table-column
        :label="$t('common.createTime')"
        align="center"
        prop="createTime"
        v-if="columns[3].visible"
      />
      <el-table-column
        :label="$t('common.operation')"
        align="center"
        prop="price"
        v-if="columns[4].visible"
      >
      <template slot-scope="scope">
        <el-button type="text" @click="handleShowNextLevel(scope.$index, scope.row)">{{ $t('common.toDetail') }}</el-button>
        <el-button v-if="scope.row.status !== 'WRITE_OFF'" type="text" @click="handleWriteOff(scope.$index, scope.row)">{{ $t('fiance.writeOff') }}</el-button>
        <el-button v-if="scope.row.status !== 'INVALID'" type="text" @click="handleAbandonment(scope.$index, scope.row)">{{ $t('common.abandon') }}</el-button>
        <!-- <el-button type="text" @click="handleCancel(scope.$index, scope.row)">{{ $t('common.cancel') }}</el-button> -->
        <!-- <el-button type="text" @click="handleDelete(scope.row)">{{ $t('common.del') }}</el-button> -->
      </template>
      </el-table-column>
    </WmsTable>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <BmsBillListAdd ref="BmsBillListAddRef" @close="getList" />
    <el-drawer :title="$t('common.toDetail')" :visible.sync="drawer" :before-close="handleClose" :size="'calc(100vw - 234px);font-size: 18px'" >
      <BmsBillDetail ref="BmsBillDetailRef" />
    </el-drawer>
    <el-dialog :title="$t('common.placeholderSelect') + '银行账号'" :visible.sync="selectAccountVisible" append-to-body width="30%">
      <el-select v-model="bankAccountNumber" :placeholder="$t('common.placeholderSelect')" clearable size="small" @focus="getAccount">
        <el-option v-for="item in bankAccountNumberList" :key="item.id" :label="item.bankAccount" :value="item.bankAccount"></el-option>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="handleExport">{{ $t('common.confirm') }}</el-button> -->
        <down-excel ref="downloadExcel" :bank-info="bankAccountNumber" :value="RowList" style="float: right;margin-left: 10px;"></down-excel>
        <el-button @click="selectAccountVisible = false">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>
    <bill-print :row="RowList ? RowList : ''" ref="printRef"></bill-print>
  </div>
</template>

<script>
import {
  bmsBillList,
  addBmsBill,
  updateBmsBill,
  delBmsBill,
  writeOff,
  createBill,
  exportBill,
  eeAccountList,
  discardBill
} from "@/api/money";
import dayjs from "dayjs";
import FormComponents from "@/components/FormComponents/index.vue";
import BmsBillDetail from './bmsBillDetail.vue'
import WmsAreaCascader from "@/components/WmsAreaCascader";
import BmsBillListAdd from "./add";
import { listWmsCustomer } from "@/api/wms/customer";
import BillPrint from "./billPrint.vue";
import downExcel from './downloadExcel.vue'
export default {
  name: "WmsReceiptOrderDetail",
  components: { WmsAreaCascader, FormComponents, BmsBillListAdd, BmsBillDetail, BillPrint, downExcel },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库龄列表
      wmStockAgeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: 'YCZ',
      },
      statusList: [
        { label: this.$t('fiance.WRITEOFF'), value: 'WRITE_OFF' },
        { label: this.$t('fiance.INVAILD'), value: 'INVAILD' },
        { label: this.$t('fiance.YCZ'), value: 'YCZ' },
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      columns: [
        { key: 1, label: this.$t('fiance.payee'), visible: true },
        { key: 2, label: this.$t('fiance.drawee'), visible: true },
        { key: 3, label: this.$t('fiance.total'), visible: true },
        { key: 4, label: this.$t('common.createTime'), visible: true },
        { key: 5, label: this.$t('common.operation'), visible: true },
      ],
      wmsCustomerList: [],
      drawer: false,
      selectAccountVisible: false,
      bankAccountNumberList: [],
      bankAccountNumber: null,
      RowList: []
    };
  },
  computed: {
    YT_roles() {
      // 暂时判断roles为common不是客户的未YT
      if(this.$store.state.user.roles[0] !== 'common') {
        return true
      }
    }
  },
  created() {
    this.getList();
  },
  methods: {
    // 查询客户
    getCusList() {
      const query = { pageNum: undefined, pageSize: undefined };
      const pageReq = { page: 0, size: 100000 };
      listWmsCustomer(query, pageReq).then((response) => {
        const { content } = response;
        this.wmsCustomerList = content;
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      const { pageNum, pageSize } = this.queryParams;
      const query = {
        ...this.queryParams,
        pageNum: undefined,
        pageSize: undefined,
      };
      const pageReq = { page: pageNum - 1, size: pageSize };
      bmsBillList(query, pageReq).then((response) => {
        const { content, totalElements } = response;
        content.map(r=>{
          r.createTime = dayjs(r.createTime).format(
            "YYYY-MM-DD HH:mm:ss"
          );
        })
        this.wmStockAgeList = content;
        this.total = totalElements;
        this.loading = false;
      });
    },
    getAccount() {
      const { pageNum, pageSize } = this.queryParams;
      const query = {
        ...this.queryParams,
        pageNum: undefined,
        pageSize: undefined,
        status: "NORMAL"
      };
      const pageReq = { page: pageNum - 1, size: pageSize };
      eeAccountList(query, pageReq).then((response) => {
        const { content, totalElements } = response;
        content.map(r=>{
          r.createTime = dayjs(r.createTime).format(
            "YYYY-MM-DD HH:mm:ss"
          );
        })
        this.bankAccountNumberList = content;
      });
    },
    handleClose() {
      this.drawer = false
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        receiptOrderNo: null,
        warehousingTime: null,
        warehouseId: null,
        customerId: null,
        customerName: null,
        receiptOrderStatus: 0,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.RowList = selection
      console.log('this.RowList', this.RowList)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = this.$t('common.add');
      this.$nextTick(() => {
        this.$refs.BmsBillListAddRef.open();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.warehousingTime = dayjs(this.form.warehousingTime).format(
            "YYYY-MM-DD HH:mm:ss"
          );
          this.form.deliveryTime = dayjs(this.form.deliveryTime).format(
            "YYYY-MM-DD HH:mm:ss"
          );
          if (this.form.id != null) {
            updateBmsBill(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t('common.succcessInfo'));
              this.open = false;
              this.getList();
            });
          } else {
            addBmsBill(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t('common.succcessInfo'));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm(this.$t('common.delMsg'))
        .then(function () {
          return delBmsBill(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t('common.succcessInfo'));
        })
        .catch(() => {});
    },
    handleShowNextLevel(index, row) {
      this.drawer = true
      this.$nextTick(() => {
        this.$refs.BmsBillDetailRef.open(row)
      })
    },
    /** 销账操作 */
    handleWriteOff(index, row) {
      this.$confirm(this.$t('common.confirmMsg') + ' ' + this.$t('fiance.writeOff') + '?', this.$t('common.reminder'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      }).then(() => {
        const params = { id: row.id }
        writeOff({...params}).then(r=>{
          if(r) {
            this.$message({
              type: 'success',
              message: this.$t('common.succcessInfo')
            });
            this.getList();
          }
        })
      }).catch(() => {});
    },
    /** 废弃操作 */
    handleAbandonment(index, row) {
      this.$confirm(this.$t('common.confirmMsg') + ' ' + this.$t('common.abandon') + '?', this.$t('common.reminder'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      }).then(() => {
        const params = { id: row.id }
        discardBill({...params}).then(r=>{
          if(r) {
            this.$message({
              type: 'success',
              message: this.$t('common.succcessInfo')
            });
            this.getList();
          }
        })
      }).catch(() => {});
    },
    // 账单取消
    handleCancel(index, row) {
      this.$confirm(this.$t('common.confirmMsg') + ' ' + this.$t('common.cancel') + this.$t('common.operation') + '?', this.$t('common.reminder'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      }).then(() => {
        const params = { id: row.id, status: 'CANCEL' }
        updateBmsBill({...params}).then((response) => {
          this.$modal.msgSuccess(this.$t('common.succcessInfo'));
          this.open = false;
          this.getList();
        });
      }).catch(() => {});
    },
    beforeHandleExport() {
      this.RowList.length > 0 ? this.selectAccountVisible = true : this.$message.warning('请至少选择一项！')
    },
    /** 导出按钮操作 */
    handleExport() {
      if(!this.bankAccountNumber) {
        this.$message.error(this.$t('common.placeholderSelect') + ' ' + this.$t('fiance.accountNo'))
      } else {
        console.log('this.$refs.downloadExcel', this.$refs.downloadExcel)
        this.$refs.downloadExcel.open()
        // const params = { bankNo: this.bankAccountNumber, customerId: this.RowList.id }
        // exportBill({...params}).then(res=>{
        //   this.$download.download(res);
        // })
      }
    },
    windowPrintOut(row, print) {
      this.$nextTick(() => {
        this.$refs["printRef"].start();
      });
    },
  },
};
</script>
